package org.zk.dubbo_consumer.controller;


import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.zk.dubbo_consumer.utils.PageUtil;
import org.zk.entity.*;
import org.zk.service.*;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.*;


import javax.servlet.http.HttpSession;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Alicelonely
 * @since 2019-12-11
 */

@RestController
@RequestMapping("/course")
public class CourseController {

    @Resource
    CourseService courseService;
    @Resource
    private LessionService lessionService;
    @Resource
    private CatalogService catalogService;
    @Resource
    private CommentService commentService;
    @Resource
    private BroadcastService broadcastService;


    /*//高申 2019-12-16 查看所有
    @RequestMapping("/queryAllCourse")
    public ModelAndView queryAllCourse(HttpSession session){

        //模拟用户登录，存放session
        User user=new User();
        user.setUserId(2);
        user.setUserName("好好学习");
        session.updateBroadcastCount(Broadcast broadcast)"user",user);

        List<Course> courses=courseService.queryAllCourse();
        Map<String,Object> maps=new HashMap<>();
        maps.put("course",courses);
        return new ModelAndView("/user/all-course",maps);
    }
*/


    /**
     * 课程详情页
     *
     * @param courseId
     * @return
     */
    @RequestMapping("/toCourseMsg")
    public ModelAndView toCourse(int courseId, HttpSession session) {

     /*   //gs修改，==============================
        //模拟用户登录，存放session
        User user = new User();
        user.setUserId(2);
        user.setUserName("好好学习");
        user.setUserVip(1);//会员
        session.setAttribute("user", user);
        //======================================*/

        Course course = courseService.queryCourse(courseId);
        Map map = new HashMap();
        map.put("courseId", courseId);

        map.put("teacherId",course.getTeacher().getTeacherId());
        int courseCount = courseService.getCourseCountByTid(map);//该教师发布的课程数量

        PageInfo courseListPage = courseService.getqueryCourseByTidPage(map);//该教师发布的所有课程
        List<Course> courseList = courseListPage.getList();
        int commentCount = commentService.getCommentCount(map);//单个课程的评价数
        List<Lession> catalog = catalogService.getCatalogByCid(courseId);

        String name = course.getCourseCover();
        String path = "/static/image/picture/" + name;
        ModelAndView modelAndView = new ModelAndView("user/courseMsg");
        modelAndView.addObject("catalog", catalog);  //目录
        modelAndView.addObject("course", course);
        modelAndView.addObject("path", path);
        modelAndView.addObject("commentCount", commentCount);
        modelAndView.addObject("courseCount", courseCount);
        modelAndView.addObject("courseList", courseList);
        return modelAndView;

    }


    @RequestMapping("/toAddCourse")
    public ModelAndView toAddCourse() {
        return new ModelAndView("/teacher/course-add");
    }

    //course表的添加
    @RequestMapping("/addCourse")
    public ModelAndView addCourse(Course course, Type type, Subject subject, @RequestParam("file") MultipartFile file, HttpSession session) {
        String fileName = file.getOriginalFilename();  // 文件名
        if (!"".equals(fileName)) {
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            File fileMkdir = new File("E:\\courseCover");
            if (!fileMkdir.exists()) {
                fileMkdir.mkdir();
            }
            String filePath = fileMkdir.getPath() + "\\";
            fileName = UUID.randomUUID() + suffixName;  //新文件名
            File dest = new File(filePath + fileName);
            try {
                //写入文件
                file.transferTo(dest);
            } catch (IOException e) {
            }
        }
        course.setSubject(subject);
        course.setType(type);
        course.setCourseCover(fileName);
//        Teacher teacher= (Teacher) session.getAttribute("teacher");
        Teacher teacher = new Teacher();
        teacher.setTeacherId(1);//模拟取值
        course.setTeacher(teacher);
        int result = courseService.insertCourse(course);
        if (result > 0) {
            return new ModelAndView("teacher/lession_add");
        } else {
            return new ModelAndView("/teacher/course-add");
        }
    }

    @RequestMapping("/toIndex")
    public ModelAndView toIndex() {
        ModelAndView modelAndView = new ModelAndView("user/index");
        return modelAndView;
    }

    @RequestMapping("/queryCourseByTid")
    public Map queryCourseByTid(int pageSize, int pageNum,int teacherId){
        Map<String, Object> map = new HashMap<>();
        map.put("teacherId",teacherId);
        map.put("pageSize", pageSize);
        map.put("pageNum", pageNum);
        PageInfo page = courseService.getqueryCourseByTidPage(map);
        List<Course> ls = page.getList();
        for (int i = 0; i < ls.size(); i++) {
            String name=ls.get(i).getCourseCover();
            ls.get(i).setCourseCover("/static/image/picture/" +name);
            String flag = ls.get(i).getCourseFlag();
            if (flag.equals("0")) {
                ls.get(i).setCourseFlag("待审核");
            }
            if (flag.equals("1")) {
                ls.get(i).setCourseFlag("已通过");
            }
            if (flag.equals("2")) {
                ls.get(i).setCourseFlag("拒绝");
            }
        }
        map.put("page", page);
        map.put("totalPage", page.getPages());
        return map;
    }


    /*删除单个的章节*/
    @ResponseBody
    @RequestMapping("/delCourseById")
    public List delCourseById(int courseId){
        List list = new ArrayList();
        int result = courseService.delCourseById(courseId);
        if (result>0){
            list.add("succ");
        }else {
            list.add("error");
        }
        return list;
    }

@RequestMapping("/toCourse")
    public ModelAndView toCourseBySid(int subjectId){
        ModelAndView mv=new ModelAndView("admin/classify/course");
        mv.addObject("subjectId",subjectId);
        return mv;
    }

    @RequestMapping("/getAllCoursePages")
    @ResponseBody
    public Map getAllCourse(String pageSize,String pageNum,int id){
        Map map=new HashMap();
        map.put("pageSize",pageSize);
        map.put("pageNum",pageNum);
        map.put("id",id);
        PageInfo page=courseService.getAllCoursesPage(map);
        map.put("page",page);
        map.put("pages",page.getPages());
        map.put("total",page.getTotal());
        return map;

    }
    @RequestMapping("/deleteCourseById")
    @ResponseBody
    public int deleteCourseById(int id){
        int result=courseService.delCourseById(id);
        return result;
    }
    /**
     * @MethodName: getCourseToIndex2
     * @Description: 综合查询所有视频和直播
     * @Param: [pageNum, pageSize, typeId, subjectId, state, courseNature, flag]
     * @Return: java.util.Map
     * @Author: 刘艺广
     * @Time: 2020/1/9 0009 下午 4:59
     **/
    @RequestMapping("/getCourseToIndex2")
    public Map getCourseToIndex2(Integer pageNum, Integer pageSize, Integer typeId, Integer subjectId, Integer state, String courseNature, Integer flag) {

        System.out.println("======================================");
        System.out.println("typeId=="+typeId+"   subjectId=="+subjectId+"  state=="+state+"  flag=="+flag+"  courseNature=="+courseNature);
        List list = new ArrayList();
        Map map = new HashMap();

        Course course = new Course();
        course.setCourseState(state);

        Broadcast broadcast = new Broadcast();
        broadcast.setBroadcastState(state);

        map.put("pageNum", pageNum);
        map.put("typeId", typeId);
        map.put("subjectId", subjectId);
        map.put("flag", flag);
        map.put("course", course);
        map.put("broadcast", broadcast);

        List<Course> courseList=new ArrayList<>();
        List<Broadcast> broadcastList=new ArrayList<>();
        if (courseNature == null) {
            courseList=courseService.getAllCourseList(map);

            System.out.println("视频查询到： "+courseList.size());

            for (int i = 0; i <courseList.size(); i++) {
                courseList.get(i).setCourseCover("/static/picture/" +courseList.get(i).getCourseCover());
                list.add(courseList.get(i));
            }

            System.out.println("添加视频后总共有"+list.size()+"条数据");
            broadcastList=broadcastService.getAllBroadcastList(map);
            System.out.println("直播查询到： "+broadcastList.size());
            for (int i = 0; i <broadcastList.size(); i++) {
                broadcastList.get(i).setBroadcastCover("/static/picture/" +broadcastList.get(i).getBroadcastCover());
                list.add(broadcastList.get(i));
            }

            System.out.println("添加直播后总共有"+list.size()+"条数据");

        } else if ("video".equals(courseNature)) {
            List<Course> courses=courseService.getAllCourseList(map);
            System.out.println("视频查询到： "+courses.size());
            for (int i = 0; i <courses.size(); i++) {
                courses.get(i).setCourseCover("/static/picture/" +courses.get(i).getCourseCover());
                list.add(courses.get(i));
            }
        } else if ("broadcast".equals(courseNature)) {
            List<Broadcast> broadcasts=broadcastService.getAllBroadcastList(map);
            System.out.println("直播查询到： "+broadcasts.size());
            for (int i = 0; i <broadcasts.size(); i++) {
                broadcasts.get(i).setBroadcastCover("/static/picture/" +broadcasts.get(i).getBroadcastCover());
                list.add(broadcasts.get(i));
            }
        }
        map.put("pageSize", pageSize);
        map.put("pageCount",list.size());

        //当前页，当前是第几条，需要取几条
        int pageIndex=pageSize*(pageNum-1);  //下一次从pageIndex开始取
        //总页数
        int pageTotal= PageUtil.getTotalPages(list.size(),pageSize);

        System.out.println("总共有"+list.size()+"条数据 ，共"+pageTotal+"页， 当前页："+pageNum+"， 应该从第 "+pageIndex+" 条开始取");

        map.put("pageTotal",pageTotal);

        //每页应该取到的结尾处
        int pageEnd=pageIndex+pageSize;
        if(pageNum>=pageTotal){
            pageEnd=list.size();
        }

        List returnList=new ArrayList();
        for (int i = pageIndex; i <pageEnd; i++) {
            returnList.add(list.get(i));
            if(Course.class.isInstance(list.get(i))){
                Course course1= (Course) list.get(i);
                System.out.println("视频："+course1.getCourseName());
            }else if(Broadcast.class.isInstance(list.get(i))){
                Broadcast broadcast1= (Broadcast) list.get(i);
                System.out.println("直播："+broadcast1.getBroadcastTitle());
            }
        }
        map.put("returnList", returnList);
        return map;
    }


    public CourseService getCourseService() {
        return courseService;
    }

    public void setCourseService(CourseService courseService) {
        this.courseService = courseService;
    }

    public LessionService getLessionService() {
        return lessionService;
    }

    public void setLessionService(LessionService lessionService) {
        this.lessionService = lessionService;
    }

    public CatalogService getCatalogService() {
        return catalogService;
    }

    public void setCatalogService(CatalogService catalogService) {
        this.catalogService = catalogService;
    }

    public CommentService getCommentService() {
        return commentService;
    }

    public void setCommentService(CommentService commentService) {
        this.commentService = commentService;
    }
}



